<template>
  <div class="hanzi-learning">
    <!-- 左右布局容器 -->
    <div class="layout-container">
      <!-- 左侧：汉字信息展示区 -->
      <div class="left-panel">
        <div class="hanzi-info">
          <div class="current-hanzi">{{ currentHanzi }}</div>
          <div class="pinyin">{{ hanziData[currentHanzi]?.pinyin || '' }}</div>
        </div>

        <!-- 笔顺演示区域 -->
        <div class="stroke-demo">
          <h4>笔顺演示</h4>
          <div class="writing-area">
            <div id="hanzi-writer-target" class="writer-target"></div>
          </div>
          <div class="demo-controls">
            <button @click="animateCharacter" class="btn btn-primary">
              📝 演示笔顺
            </button>
            <button @click="resetCharacter" class="btn btn-secondary">
              🔄 重新开始
            </button>
          </div>
        </div>
      </div>

      <!-- 右侧：汉字选择区 -->
      <div class="right-panel">
        <div class="hanzi-selector">
          <h3>选择汉字</h3>
          
          <!-- 搜索框 -->
          <div class="search-container">
            <input 
              v-model="searchText" 
              @input="handleSearch"
              placeholder="搜索汉字或拼音..." 
              class="search-input"
            />
          </div>
          
          <!-- 年级筛选 -->
          <div class="grade-filter">
            <label>年级筛选：</label>
            <select v-model="selectedGrade" @change="handleGradeChange" class="grade-select">
              <option value="">全部</option>
              <option v-for="grade in grades" :key="grade" :value="grade">{{ grade }}</option>
            </select>
          </div>
          
          <!-- 汉字按钮区域 -->
          <div class="hanzi-buttons">
            <button 
              v-for="item in paginatedHanziList" 
              :key="item.hanzi"
              :class="{ active: currentHanzi === item.hanzi }"
              @click="changeHanzi(item.hanzi)"
              class="hanzi-btn"
            >
              {{ item.hanzi }}
              <span class="hanzi-info-small">{{ item.pinyin }}</span>
            </button>
          </div>
          
          <!-- 分页控件 -->
          <div class="pagination">
            <button 
              @click="prevPage" 
              :disabled="currentPage === 1"
              class="page-btn"
            >
              ◀
            </button>
            <span class="page-info">
              第 {{ currentPage }} 页 / 共 {{ totalPages }} 页
              ({{ filteredHanziList.length }} 个汉字)
            </span>
            <button 
              @click="nextPage" 
              :disabled="currentPage === totalPages"
              class="page-btn"
            >
              ▶
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from "vue";
import { useRoute } from "vue-router";
import HanziWriter from "hanzi-writer";

import { resolveResource } from '@tauri-apps/api/path';
import { readTextFile } from '@tauri-apps/plugin-fs';

// 响应式数据
const allHanziData = ref<Array<{grade: string, hanzi: string, pinyin: string}>>([]);
const hanziData = ref<{[key: string]: {pinyin: string, meaning: string, words: string[]}}>({});
const searchText = ref("");
const selectedGrade = ref("");
const currentPage = ref(1);
const pageSize = ref(12); // 每页显示12个汉字

// 计算属性
const grades = computed(() => {
  const gradeSet = new Set(allHanziData.value.map(item => item.grade));
  const gradeOrder = ["一年级", "二年级", "三年级", "四年级", "五年级", "六年级"];
  return Array.from(gradeSet).sort((a, b) => {
    return gradeOrder.indexOf(a) - gradeOrder.indexOf(b);
  });
});

// 过滤后的汉字列表
const filteredHanziList = computed(() => {
  let filtered = allHanziData.value;
  
  // 年级筛选
  if (selectedGrade.value) {
    filtered = filtered.filter(item => item.grade === selectedGrade.value);
  }
  
  // 搜索筛选
  if (searchText.value.trim()) {
    const searchLower = searchText.value.toLowerCase().trim();
    filtered = filtered.filter(item => 
      item.hanzi.includes(searchLower) || 
      item.pinyin.toLowerCase().includes(searchLower)
    );
  }
  
  return filtered;
});

// 分页相关计算属性
const totalPages = computed(() => Math.ceil(filteredHanziList.value.length / pageSize.value));
const paginatedHanziList = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value;
  const endIndex = startIndex + pageSize.value;
  return filteredHanziList.value.slice(startIndex, endIndex);
});

// 加载CSV数据
const loadCSVData = async () => {
  try {
    const resourcePath = await resolveResource('data/primary_school_chinese.csv');
    const csvText = await readTextFile(resourcePath);
    
    // 解析CSV数据
    const lines = csvText.split('\n').slice(1); // 跳过标题行
    const data = [];
    
    for (const line of lines) {
      if (line.trim()) {
        const [grade, hanzi, pinyin] = line.split(',');
        if (hanzi && pinyin) {
          data.push({
            grade: grade.trim(),
            hanzi: hanzi.trim(),
            pinyin: pinyin.trim()
          });
        }
      }
    }
    
    allHanziData.value = data;
    
    // 构建hanziData对象
    const hanziMap: {[key: string]: {pinyin: string, meaning: string, words: string[]}} = {};
    data.forEach(item => {
      hanziMap[item.hanzi] = {
        pinyin: item.pinyin,
        meaning: `${item.hanzi}，${getDefaultMeaning(item.hanzi)}`,
        words: getDefaultWords(item.hanzi)
      };
    });
    
    hanziData.value = hanziMap;
    
  } catch (error) {
    console.error('加载CSV数据失败:', error);
    // 如果加载失败，使用默认数据
    allHanziData.value = [
      { grade: "一年级", hanzi: "人", pinyin: "rén" },
      { grade: "一年级", hanzi: "口", pinyin: "kǒu" },
      { grade: "一年级", hanzi: "日", pinyin: "rì" },
      { grade: "一年级", hanzi: "月", pinyin: "yuè" },
      { grade: "一年级", hanzi: "水", pinyin: "shuǐ" }
    ];
    
    hanziData.value = {
      "人": { pinyin: "rén", meaning: "人，人类，人物", words: ["人民", "人类", "人物", "大人", "小人"] },
      "口": { pinyin: "kǒu", meaning: "口，嘴巴，出入口", words: ["人口", "门口", "出口", "入口", "口水"] },
      "日": { pinyin: "rì", meaning: "日，太阳，日子", words: ["日子", "生日", "日本", "日光", "节日"] },
      "月": { pinyin: "yuè", meaning: "月，月亮，月份", words: ["月亮", "月光", "月份", "月饼", "月球"] },
      "水": { pinyin: "shuǐ", meaning: "水，液体，水流", words: ["水果", "水杯", "河水", "海水", "水彩"] }
    };
  }
};

// 获取默认含义
const getDefaultMeaning = (hanzi: string) => {
  const meanings: {[key: string]: string} = {
    "人": "人类，人物",
    "口": "嘴巴，出入口",
    "日": "太阳，日子",
    "月": "月亮，月份",
    "水": "液体，水流"
  };
  return meanings[hanzi] || "常用汉字";
};

// 获取默认词语
const getDefaultWords = (hanzi: string) => {
  const wordsMap: {[key: string]: string[]} = {
    "人": ["人民", "人类", "人物", "大人", "小人"],
    "口": ["人口", "门口", "出口", "入口", "口水"],
    "日": ["日子", "生日", "日本", "日光", "节日"],
    "月": ["月亮", "月光", "月份", "月饼", "月球"],
    "水": ["水果", "水杯", "河水", "海水", "水彩"]
  };
  return wordsMap[hanzi] || [`${hanzi}字`, `${hanzi}语`, `${hanzi}文`];
};

const route = useRoute();
const currentHanzi = ref("人");
const writer = ref<HanziWriter | null>(null);

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1; // 搜索时重置到第一页
};

// 年级筛选处理
const handleGradeChange = () => {
  currentPage.value = 1; // 筛选时重置到第一页
};

// 分页处理
const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--;
  }
};

const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++;
  }
};

// 初始化汉字书写器
onMounted(async () => {
  // 加载CSV数据
  await loadCSVData();
  
  // 检查URL参数
  if (route.query.hanzi && hanziData.value[route.query.hanzi as string]) {
    currentHanzi.value = route.query.hanzi as string;
  }
  
  initWriter();
});

onUnmounted(() => {
  if (writer.value) {
    writer.value = null;
  }
});

const initWriter = () => {
  const target = document.getElementById('hanzi-writer-target');
  if (target && currentHanzi.value && hanziData.value[currentHanzi.value]) {
    // 先清空画布内容
    target.innerHTML = '';
    
    if (writer.value) {
      writer.value = null;
    }
    
    writer.value = HanziWriter.create(target, currentHanzi.value, {
      width: 250,
      height: 250,
      padding: 5,
      showOutline: true,
      strokeColor: '#FF6B6B',
      radicalColor: '#4ECDC4',
      strokeAnimationSpeed: 2,
      delayBetweenStrokes: 400,
      showCharacter: false,
    });
  }
};

const changeHanzi = (hanzi: string) => {
  if (hanziData.value[hanzi]) {
    currentHanzi.value = hanzi;
    setTimeout(() => {
      initWriter();
    }, 100);
  }
};

const animateCharacter = () => {
  if (writer.value) {
    writer.value.animateCharacter();
  }
};

const resetCharacter = () => {
  if (writer.value) {
    writer.value.hideCharacter();
  }
};
</script>

<style scoped>
.hanzi-learning {
  margin: 0 auto;
  height: 100%;
}

.layout-container {
  display: flex;
  gap: 20px;
  height: 100%;
  min-height: 500px; /* 设置最小高度，但允许自适应 */
}

.left-panel {
  flex: 2;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.right-panel {
  flex: 1;
  min-width: 300px;
}

.hanzi-selector {
  background: white;
  padding: 20px;
  border-radius: 15px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  height: 100%;
  box-sizing: border-box;
}

.hanzi-selector h3 {
  color: #ff6b6b;
  margin-bottom: 15px;
  text-align: center;
  font-size: 1.3rem;
}

.hanzi-buttons {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 8px;
}

.hanzi-btn {
  padding: 10px;
  font-size: 1.4rem;
  border: none;
  border-radius: 8px;
  background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  min-height: 50px;
}

.hanzi-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
}

.hanzi-btn.active {
  background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);
  color: white;
  transform: scale(1.05);
}

.hanzi-info {
  background: white;
  padding: 20px;
  border-radius: 15px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  text-align: center;
  flex: 1;
}

.current-hanzi {
  font-size: 4rem;
  color: #ff6b6b;
  margin-bottom: 10px;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
}

.pinyin {
  font-size: 1.3rem;
  color: #4ecdc4;
  margin-bottom: 5px;
}

.meaning {
  font-size: 1.1rem;
  color: #666;
}

.stroke-demo {
  background: white;
  padding: 20px;
  border-radius: 15px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  text-align: center;
  flex: 2;
}

.stroke-demo h4 {
  color: #ff6b6b;
  margin-bottom: 15px;
  font-size: 1.2rem;
}

.writing-area {
  margin: 15px 0;
  display: flex;
  justify-content: center;
}

.writer-target {
  border: 3px dashed #ffd166;
  border-radius: 15px;
  background: #fffaf0;
  padding: 10px;
}

.demo-controls {
  display: flex;
  gap: 10px;
  justify-content: center;
  margin-top: 15px;
}

.btn {
  padding: 10px 16px;
  border: none;
  border-radius: 20px;
  font-size: 0.9rem;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.btn-primary {
  background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);
  color: white;
}

.btn-secondary {
  background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
  color: #333;
}

.btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
}

/* 搜索和筛选样式 */
.search-container {
  margin-bottom: 15px;
}

.search-input {
  width: 90%;
  padding: 10px 15px;
  border: 2px solid #e0f7fa;
  border-radius: 25px;
  font-size: 0.9rem;
  outline: none;
  transition: all 0.3s ease;
  background: #f8fdff;
}

.search-input:focus {
  border-color: #4ecdc4;
  box-shadow: 0 0 0 3px rgba(78, 205, 196, 0.1);
}

.grade-filter {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.grade-filter label {
  font-size: 0.9rem;
  color: #666;
  font-weight: 500;
}

.grade-select {
  padding: 8px 12px;
  border: 2px solid #e0f7fa;
  border-radius: 20px;
  font-size: 0.9rem;
  outline: none;
  background: #f8fdff;
  cursor: pointer;
  transition: all 0.3s ease;
}

.grade-select:focus {
  border-color: #4ecdc4;
  box-shadow: 0 0 0 3px rgba(78, 205, 196, 0.1);
}

/* 汉字按钮中的拼音样式 */
.hanzi-info-small {
  display: block;
  font-size: 0.7rem;
  color: #666;
  margin-top: 5px;
  font-weight: normal;
}

/* 分页控件样式 */
.pagination {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 15px;
  margin-top: 20px;
  padding-top: 15px;
  border-top: 1px solid #f0f0f0;
}

.page-btn {
  padding: 8px 12px;
  border: 2px solid #e0f7fa;
  border-radius: 20px;
  background: #f8fdff;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 1rem;
  color: #4ecdc4;
}

.page-btn:hover:not(:disabled) {
  background: #4ecdc4;
  color: white;
  transform: translateY(-1px);
}

.page-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  transform: none;
}

.page-info {
  font-size: 0.9rem;
  color: #666;
  text-align: center;
  min-width: 180px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .layout-container {
    flex-direction: column;
    max-height: none;
  }
  
  .right-panel {
    min-width: auto;
  }
  
  .hanzi-buttons {
    grid-template-columns: repeat(4, 1fr);
  }
  
  .current-hanzi {
    font-size: 3rem;
  }
  
  .demo-controls {
    flex-direction: column;
  }
  
  .grade-filter {
    flex-direction: column;
    align-items: stretch;
  }
  
  .pagination {
    flex-direction: column;
    gap: 10px;
  }
  
  .page-info {
    min-width: auto;
  }
}
</style>